const { Pool, Client } = require('pg')
const pool = new Pool({
    connectionString:'postgresql://postgres:postgres@localhost:5432/xxx'
})

const express = require('express'),
      http = require('http'),
      app = express(),
      server = http.createServer(app),
      io = require('socket.io').listen(server);

app.use(express.static(__dirname + '/public'));

app.get('/', (req, res) => {
    //res.send('Chat Server is running on port 3000')
    res.sendFile(__dirname + '/index.html');
});
const tag = 'xxx'
io.on('connection', (socket) => {

    var address = socket.handshake.address;
    let msg = address + ' connected'
    console.log(msg)
    io.emit(tag, msg)

    socket.on(tag, (msg) => {
	console.log('message: ' + msg);
	msg = JSON.parse(msg)
	// except the emitting socket
	socket.broadcast.emit(tag,msg.src +": "+msg.txt);
	// to everyone
	//io.emit(tag, msg)

	const sql = "INSERT INTO msg(timestamp, txt, src) VALUES($1, $2, $3)"
	const timestamp = Math.round(new Date().getTime()/1000)
	console.log(timestamp)
	const argv = [timestamp, msg.txt, msg.src]
	pool.query(sql, argv) .catch(e => console.error(e.stack))
    });

    //io.emit('message', 'welcome');
    socket.on('join', function(userNickname) {

	console.log(userNickname +" : has joined the chat "  );

	socket.broadcast.emit(tag,userNickname +" : has joined the chat ");
    });


    socket.on('messagedetection', (senderNickname,messageContent) => {
	
	//log the message in console 

	console.log(senderNickname+" :" +messageContent)
	//create a message object 
	let  message = {"message":messageContent, "senderNickname":senderNickname}
	// send the message to the client side  
	io.emit('message', message );
	
    });
    
    
    socket.on('disconnect', function() {
	let msg = address + ' has left '
	console.log(msg)
	socket.broadcast.emit(tag,msg) 

    });



});





server.listen(3000,()=>{

    console.log('Node app is running on port 3000');

});
